﻿using ApplicationBase.Core.Domain;
using ApplicationBase.Core.Extensions;
using IdentityService.Domain.Aggregates.PermitAggregate;
using IdentityService.Domain.Aggregates.RoleAggregate;
using IdentityService.Domain.Aggregates.UserAccountAggregate;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace IdentityService.Infrastructure
{
    public class AppIdentityDbContext : DbContext, IUnitOfWork
    {
        private readonly IMediator _mediator;

        public AppIdentityDbContext(DbContextOptions<AppIdentityDbContext> options, IMediator mediator) : base(options)
            => _mediator = mediator;

        public DbSet<UserAccount> UserAccount { get; set; }
        public DbSet<UserInfo> UserInfo { get; set; }
        public DbSet<UserAccountClaim> UserAccountClaim { get; set; }
        public DbSet<Role> Role { get; set; }
        public DbSet<RolePermit> RolePremit { get; set; }
        //public DbSet<RoleClaim> RoleClaim { get; set; }
        public DbSet<Permit> Permit { get; set; }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            builder.ApplyConfigurationsFromAssembly(typeof(AppIdentityDbContext).Assembly);
        }

        public async Task<int> SaveEntitiesAsync(CancellationToken cancellationToken = default)
        {
            await _mediator.DispatchDomainEventsAsync(this);
            return await base.SaveChangesAsync(cancellationToken);
        }
    }
}
